

//
//  XiaoShouVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/22.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SCLAlertView
import SVProgressHUD
import os.log

class XiaoShouVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var addButton: UIButton!
    var rightBarItem: UIBarButtonItem!
    
    var items = [Sale.XiaoShou]()
    var material: MaterialDetail!
    var selectedColor: CodableColorOfMaterial!
    
    var shoppingLists = [ShoppingList]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0)
        tableView.delegate = self
        tableView.dataSource = self
        rightBarItem = UIBarButtonItem(title: "加入清单", style: .plain, target: self, action: #selector(rightBarButtonTapped(_:)))
        navigationItem.setRightBarButtonItems([rightBarItem], animated: true)
        addButton.addTarget(self, action: #selector(addButtonTapped(_:)), for: .touchUpInside)
        tableView.register(UINib(nibName: "XIaoShouCell", bundle: nil), forCellReuseIdentifier: "XiaoShouCell")
        
    }
    
    
    @objc func rightBarButtonTapped(_ button: UIBarButtonItem!) {
        guard items.count > 0 else {
            showError(message: "未选择任何面料")
            return
        }
        SVProgressHUD.show()
        saveFile { (_) in
            SVProgressHUD.dismiss()
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    
    @objc func addButtonTapped(_ button: UIButton!) {
        let appearence = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: true, hideWhenBackgroundViewIsTapped: true)
        
        let alertView = SCLAlertView(appearance: appearence)
        let nextAlertView = SCLAlertView(appearance: appearence)
        for color in material.color {
            alertView.addButton("\(color.no)-\(color.color)（\(color.stock)）", action: {
                self.selectedColor = color
                let textField = nextAlertView.addTextField("请输入销售数量（最多\(color.stock)）")
                textField.keyboardType = .numberPad
                nextAlertView.addButton("确定", action: {
                    guard let text = textField.text.nilIfEmpty else {
                        return
                    }
                    guard Int(text)! < color.stock else {
                        SVProgressHUD.showError(withStatus: "该颜色库存不足")
                        SVProgressHUD.dismiss(withDelay: 2.5)
                        return
                    }
                    self.items.append(Sale.XiaoShou(materialId: self.material.id, colorId: color.id!, number: text, price: self.material.price, unit: self.material.unit))
                    let shopping = ShoppingList(materialId: self.material.id, materialName: self.material.name, colorNo: color.no, color: color.color, colorId: color.id!, number: text, price: self.material.price, unit: self.material.unit)
                    self.shoppingLists.append(shopping)
                    self.tableView.beginUpdates()
                    self.tableView.insertRows(at: [IndexPath(row: self.items.count-1, section: 0)], with: .automatic)
                    self.tableView.endUpdates()
                })
                nextAlertView.showEdit("销售数量", subTitle: "", animationStyle: .rightToLeft)
            })
        }
        alertView.showInfo("选择销售颜色", subTitle: "", animationStyle: .topToBottom)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "XiaoShouCell") as! XIaoShouCell
        cell.numberLabel.text = items[indexPath.row].number
        cell.colorLabel.text = "\(selectedColor.no)-\(selectedColor.color)"
        cell.deleteButton.addTarget(self, action: #selector(deleteBtTapped(_:)), for: .touchUpInside)
        cell.selectionStyle = .none
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
    @objc func deleteBtTapped(_ button: UIButton!) {
        let point = button.convert(CGPoint.zero, to: tableView)
        guard let indexPath = tableView.indexPathForRow(at: point) else {
            return
        }
        items.remove(at: indexPath.row)
        tableView.beginUpdates()
        tableView.deleteRows(at: [indexPath], with: .automatic)
        tableView.endUpdates()
    }
    
    private func saveFile(completeHandler: @escaping (Bool) -> Void) {
        if let originLists = loadFile() {
            for item in originLists {
                shoppingLists.append(item)
            }
        }
        let queue = DispatchQueue(label: "save_file")
        queue.async {
            let isSuccess = NSKeyedArchiver.archiveRootObject(self.shoppingLists, toFile: ShoppingList.ArchiveURL.path)
            if isSuccess {
                os_log("Successful save file", log: .default, type: .debug)
                DispatchQueue.main.async {
                    completeHandler(isSuccess)
                }
            } else {
                os_log("not successful", log: .default, type: .debug)
                DispatchQueue.main.async {
                    completeHandler(isSuccess)
                }
            }
        }
    }
    private func loadFile() -> [ShoppingList]? {
        return NSKeyedUnarchiver.unarchiveObject(withFile: ShoppingList.ArchiveURL.path) as? [ShoppingList]
    }

}
